/*
 * Copyright 2011 myTDev.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mytdev.commons.text.parsers;

import com.mytdev.commons.text.AbstractParser;
import java.awt.Color;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 *
 * @author Yann D'Isanto
 */
public class ColorParser extends AbstractParser<Color> {

    private static final Pattern COLOR_PATTERN = Pattern.compile("#[0-9a-zA-Z]{6}");
    private static final Map<String, Color> COLORS = new HashMap<String, Color>();

    static {
        COLORS.put("black", Color.BLACK);
        COLORS.put("blue", Color.BLUE);
        COLORS.put("cyan", Color.CYAN);
        COLORS.put("darkgray", Color.DARK_GRAY);
        COLORS.put("gray", Color.GRAY);
        COLORS.put("green", Color.GREEN);
        COLORS.put("lightgray", Color.LIGHT_GRAY);
        COLORS.put("magenta", Color.MAGENTA);
        COLORS.put("orange", Color.ORANGE);
        COLORS.put("pink", Color.PINK);
        COLORS.put("red", Color.RED);
        COLORS.put("white", Color.WHITE);
        COLORS.put("yellow", Color.YELLOW);
    }

    public ColorParser() {
        super(Color.class);
    }

    @Override
    public Color parse(String string) throws ParseException {
        string = string.trim();
        Color color = COLORS.get(string.toLowerCase());
        if (color == null) {
            if (!COLOR_PATTERN.matcher(string).matches()) {
                throw new ParseException("invalid color", 0);
            }
            int r = Integer.parseInt(string.substring(1, 3), 16);
            int g = Integer.parseInt(string.substring(3, 5), 16);
            int b = Integer.parseInt(string.substring(5, 7), 16);
            color = new Color(r, g, b);
        }
        return color;
    }
}
